#!/bin/sh /etc/rc.common

START=98
USE_PROCD=1

PROG_NAME="xfrpc"
PROG_UCI_CONF="$PROG_NAME"
PROG_COMMAND=$(which "$PROG_NAME")

MACADDR=$(ifconfig br-lan | grep HWaddr | awk '{print $5}'| sed 's/://g')
PROG_CONFIG_FILE="/var/etc/xfrpc.ini"
PROXY_COUNT=0

append_section() {
	[ -f "$PROG_CONFIG_FILE" ] && echo '' >> $PROG_CONFIG_FILE
	echo "$1" >> $PROG_CONFIG_FILE
}

append_key_value() {
	local section="$1"
	local option="$2"
	local key="$3"
	local _value

	config_get _value "$section" "$option"
	[ -z "$_value" ] && return 1

	echo "${key#--} = $_value" >> $PROG_CONFIG_FILE
}

xfrpc_config_set() {
	local section="$1"
	local option="$2"
	local value="$3"

	uci set xfrpc.${1}.${option}="$value"
	uci commit xfrpc
}

xfrpc_validate_common() {
	uci_validate_section xfrpc common "${1}" \
		'server_addr:string' \
		'server_port:uinteger'
}

xfrpc_parse_common() {
	local cfg="$1"
	local server_addr server_port

	xfrpc_validate_common "$cfg" || {
		echo "Section common validation failed!"
		exit 1
	}

	append_section "[common]"
	append_key_value "$cfg" server_addr "--server_addr"
	append_key_value "$cfg" server_port "--server_port"
	append_key_value "$cfg" auth_token "--auth_token"

	# Privilege mode
	append_key_value "$cfg" privilege_token "--privilege_token"

	# Connect frps by HTTP PROXY
	append_key_value "$cfg" http_proxy "--http_proxy"

	# Log
	append_key_value "$cfg" log_file "--log_file"
	append_key_value "$cfg" log_level "--log_level"
	append_key_value "$cfg" log_max_days "--log_max_days"
}

xfrpc_parse_proxy() {
	local cfg="$1"
	local section_name
	local local_port

	config_get local_port "$cfg" local_port
	[ -z "$local_port" ] && return 1

	config_get name "$cfg" name
	[ -z "$name" ] && xfrpc_config_set ${1} name "$(date +%s)"

	config_get section_name "$cfg" section_name
	[ -z "$section_name" ] && {
		local r=$(cat /proc/sys/kernel/random/uuid | cut -d "-" -f2 | tr [a-z] [A-Z])
		section_name="${MACADDR}_${name:-KUNTENG}_${r}"
		xfrpc_config_set ${1} section_name "$section_name"
	}

	append_section "[${section_name}]"

	PROXY_COUNT=`expr $PROXY_COUNT + 1`
	append_key_value "$cfg" type "--type"
	append_key_value "$cfg" local_port "--local_port"
	append_key_value "$cfg" local_ip "--local_ip"
	append_key_value "$cfg" remote_port "--remote_port"
	append_key_value "$cfg" auth_token "--auth_token"

	# gukq 20170710 add remote_data_port for ftp supportting
	append_key_value "$cfg" remote_data_port "--remote_data_port"
	# append over
	
	# Privilege Mode
	append_key_value "$cfg" privilege_mode "--privilege_mode"

	# Encryption and Compression
	append_key_value "$cfg" use_encryption "--use_encryption"
	append_key_value "$cfg" use_gzip "--use_gzip"

	# Connection Pool
	append_key_value "$cfg" pool_count "--pool_count"

	# Web service
	append_key_value "$cfg" subdomain "--subdomain"
	append_key_value "$cfg" custom_domains "--custom_domains"
	append_key_value "$cfg" host_header_rewrite "--host_header_rewrite"
	append_key_value "$cfg" http_user "--http_user"
	append_key_value "$cfg" http_pwd "--http_pwd"
	append_key_value "$cfg" locations "--locations"
}

init_config() {
	[ -f "$PROG_CONFIG_FILE" ] && rm -f "$PROG_CONFIG_FILE"

	config_load "$PROG_UCI_CONF"

	config_foreach xfrpc_parse_common server
	config_foreach xfrpc_parse_proxy proxy
}

init_rule() {
	if ! iptables -t nat -L prerouting_lan_rule | grep -q prerouting_to_frps; then
		local frps_addr=$(uci -q get xfrpc.common.server_ip)
		[ -n "$frps_addr" ] && {
			iptables -t nat -N prerouting_to_frps
			iptables -t nat -A prerouting_lan_rule -p tcp -d wifi.kunteng.org --dport 20000:65443 -j prerouting_to_frps
			iptables -t nat -A OUTPUT -p tcp -d wifi.kunteng.org --dport 20000:65443 -j prerouting_to_frps
			iptables -t nat -A prerouting_to_frps -j DNAT --to-destination $frps_addr
		}
	fi

	grep -q frps /etc/firewall.user 2>/dev/null
	[ $? == 0 ] && return 0

	cat <<-EOF >>/etc/firewall.user

	# for xfrpc
	if ! iptables -t nat -L prerouting_lan_rule | grep -q prerouting_to_frps; then
	    frps_addr=\$(uci -q get xfrpc.common.server_ip)
	    [ -n "\$frps_addr" ] && {
	        iptables -t nat -N prerouting_to_frps
	        iptables -t nat -A prerouting_lan_rule -p tcp -d wifi.kunteng.org --dport 20000:65443 -j prerouting_to_frps
	        iptables -t nat -A OUTPUT -p tcp -d wifi.kunteng.org --dport 20000:65443 -j prerouting_to_frps
	        iptables -t nat -A prerouting_to_frps -j DNAT --to-destination \$frps_addr
	    }
	fi

	exit 0
EOF
}

service_triggers() {
	procd_add_reload_trigger "$PROG_UCI_CONF"
}

start_service() {
	# init_rule

	[ ! -d "/var/etc/" ] && mkdir -p /var/etc/

	init_config

	[ $PROXY_COUNT -eq 0 ] && exit 0

	procd_open_instance
	procd_set_param command $PROG_COMMAND -c $PROG_CONFIG_FILE -f -d 0
	procd_set_param file "$PROG_UCI_CONF"
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-10} ${respawn_retry:-0}
	procd_close_instance
}
